__author__ = 'soso_fy'

#codeing:utf-8


# 写python脚本经常要用到的一些函数
# 免得每次都重写蛋疼
# require python 3.2 or later

import os
import codecs
import sys

# 读取文本文件函数，支持bom-utf-8，utf-8,utf-16,gbk,gb2312
# 返回文件内容
def readTextFile(filepath):
    try:
        file = open(filepath, 'rb')
    except IOError as err:
        print('读取文件出错 in ReadFile', err)
    bytes = file.read()
    file.close()
    if bytes[:3] == codecs.BOM_UTF8:
        content = bytes[3:].decode('utf-8')
    else:
        try:
            content = bytes.decode('gb2312')
        except UnicodeDecodeError as err:
            try:
                content = bytes.decode('utf-16')
            except UnicodeDecodeError as err:
                try:
                    content = bytes.decode('utf-8')
                except UnicodeDecodeError as err:
                    try:
                        content = bytes.decode('gbk')
                    except UnicodeDecodeError as err:
                        content = ''
                        print('不支持此种类型的文本文件编码', err)
    return content

# 获取指定路径下所有指定后缀的文件
# dir 指定路径
# ext 指定后缀，链表&不需要带点或者不指定。例子：['xml', 'java']
def getFileFromThisRootDir(dir, ext = None):
    allfiles = []
    needExtFilter = (ext is not None)
    if needExtFilter:
        ext = list(map(lambda x:x.lower(), ext))
    for root,dirs,files in os.walk(dir):
        for filespath in files:
            filepath = os.path.join(root, filespath).lower()
            extension = os.path.splitext(filepath)[1][1:]
            if needExtFilter and extension in ext:
                allfiles.append(filepath)
            elif not needExtFilter:
                allfiles.append(filepath)
    return allfiles

	
# 获取包括调用该函数的函数名，代码所在的函数
# 返回两个值，字符型的函数名，数字的行号
def get_cur_info():
    try:
        raise Exception
    except:
        f = sys.exc_info()[2].tb_frame.f_back
        return f.f_code.co_name, f.f_lineno
		

